<template>
	<div class="tabs-box">
		<div class="tabs-menu">
			<suspense>
				<template #default>
					<component
						:is="activeComponent"
						v-model="tabsMenuValue"
						:tabs-menu-list="tabsMenuList"
						:theme-config="themeConfig"
						@tab-click="tabClick"
						@tab-remove="tabRemove"
					/>
				</template>
				<template #fallback>
					<Loading />
				</template>
			</suspense>
			<MoreButton />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { GlobalStore } from '@/stores'
import { TabsStore } from '@/stores/modules/tabs'
import Loading from '@/components/Loading/index.vue'
import MoreButton from './components/MoreButton.vue'

const Components: { [key: string]: any } = {
	normal: defineAsyncComponent(() => import('./components/NormalTabs/index.vue')),
	chrome: defineAsyncComponent(() => import('./components/ChromeTabs/index.vue')),
	button: defineAsyncComponent(() => import('./components/ButtonTabs/index.vue'))
}

const route = useRoute()
const router = useRouter()
const tabStore = TabsStore()
const globalStore = GlobalStore()

const tabsMenuValue = ref(route.path)
const tabsMenuList = computed(() => tabStore.tabsMenuList)

const themeConfig = computed(() => globalStore.themeConfig)

const activeComponent = computed(() => Components[themeConfig.value.tabsType])

// 监听路由的变化（防止浏览器后退/前进不变化 tabsMenuValue）
watch(
	() => route.path,
	() => {
		tabsMenuValue.value = route.path
		const tabsParams = {
			icon: route.meta.icon as string,
			title: route.meta.title as string,
			path: route.path,
			query: route.query,
			params: route.params,
			close: !route.meta.isAffix
		}
		tabStore.addTabs(tabsParams)
	},
	{
		immediate: true
	}
)

// Tab Click
const tabClick = (obj: any) => {
	router.push(obj)
}

// Remove Tab
const tabRemove = (path: string) => {
	tabStore.removeTabs(path, path == route.path)
}
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
